package hz.mobileproject.pda.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Observer;
import java.util.logging.Logger;

import butterknife.BindView;
import cn.droidlover.xdroidmvp.mvp.XActivity;
import hz.mobileproject.pda.R;
import hz.mobileproject.pda.app.MainApp;
import hz.mobileproject.pda.db.DBManager;
import hz.mobileproject.pda.entity.request.Request_loadPrisonerList;
import hz.mobileproject.pda.entity.response.Response_loadPrisonerList;
import hz.mobileproject.pda.entity.response.Response_login_user;
import hz.mobileproject.pda.presenter.PLogin_data;
import hz.mobileproject.pda.push.mqtt.MqttClientMgr;
import hz.mobileproject.pda.ui.IndexActivity;
import hz.mobileproject.pda.utils.EditTextClearTools;

//import hz.mobileproject.pda.push.OnLoginProgress;

public class LoginActivity extends XActivity<PLogin_data> {
    /**
     * 上次点击时间
     */
    private long lastClick = 0;


    @BindView(R.id.ImageView1)
    ImageView ImageView1;
    @BindView(R.id.phonenumber)
    EditText phonenumber;
    @BindView(R.id.del_phonenumber)
    ImageView delPhonenumber;
    @BindView(R.id.relativeLayout1)
    RelativeLayout relativeLayout1;
    @BindView(R.id.ImageView2)
    ImageView ImageView2;
    @BindView(R.id.password)
    EditText password;
    @BindView(R.id.del_password)
    ImageView delPassword;
    @BindView(R.id.relativeLayout2)
    RelativeLayout relativeLayout2;
    @BindView(R.id.portrait)
    ImageView portrait;
    @BindView(R.id.loginButton)
    Button loginButton;
//    private OnLoginProgress onLoginProgress;
    private Observer onLoginSucessObserver;
    private Gson gson;
    private DBManager dBManager;
    private SPUtils spUtils;

    //进入配置页面变量
    //设置点击进入配置页面次数
    private final int mintTargetClickNum = 8;
    //设置点击时间间隔
    private final long mlongMinTime = 1500;
    //上次点击记录时间
    private long mlongUpTime;
    //点击次数
    private int mintClickNum;

    @Override
    protected void onResume() {
        super.onResume();
        phonenumber.requestFocus();

    }

    private boolean isFastClick() {
        long now = System.currentTimeMillis();
        if (now - lastClick >= 200) {  //2秒
            lastClick = now;
            return false;
        }
        return true;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initPermission();
        phonenumber=(EditText)findViewById(R.id.phonenumber);
        password=(EditText)findViewById(R.id.password);
        delPhonenumber=(ImageView)findViewById(R.id.del_phonenumber);
        delPassword=(ImageView)findViewById(R.id.del_password);
        loginButton=(Button)findViewById(R.id.loginButton);
        portrait = (ImageView)findViewById(R.id.portrait);

        EditTextClearTools.addclerListener(phonenumber, delPhonenumber);
        EditTextClearTools.addclerListener(password, delPassword);

        portrait.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                long nowTime = System.currentTimeMillis();
                if (nowTime - mlongUpTime < mlongMinTime){
                    mintClickNum++;
                }else {
                    mintClickNum = 0;
                }
                mlongUpTime = nowTime;
                if (mintClickNum == mintTargetClickNum -1){
                    mintClickNum = 0;
                    ToastUtils.showLong("进入配置页面");
                    startActivity(new Intent(LoginActivity.this, TestSettingActivity.class));
                }
            }
        });

        dBManager = DBManager.getInstance(getApplicationContext());
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(phonenumber.getText().toString())||TextUtils.isEmpty(password.getText().toString())){

                }else {


                    //判断是否快速点击
                    if (!isFastClick()) onWidgetClick(v);
                    try {

                        MessageDigest md5 = MessageDigest.getInstance("MD5");
                        String pwd = new BigInteger(1, md5.digest((password.getText().toString()+"|"+phonenumber.getText().toString()).getBytes())).toString(32);

                        getP().loadData(phonenumber.getText().toString(), pwd);

                    } catch (NoSuchAlgorithmException e) {
                        e.printStackTrace();
                    }
                }
            }


        });

    }

    @Override
    public void initData(Bundle savedInstanceState) {
        spUtils = SPUtils.getInstance("app_login");


    }


    private void initPermission() {
        PermissionUtils permission = PermissionUtils.permission(PermissionUtils.getPermissions().toArray(new String[]{}));
        permission.request();
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public PLogin_data newP() {
        return new PLogin_data();
    }

    public void showError(Throwable error) {
        if (error != null) {


        }
    }

    public void showData(String model) {
        Log.e("tag_login",model);
        gson = new Gson();
        Response_login_user  login_user= gson.fromJson(model,Response_login_user.class);

        spUtils.put("police_code",login_user.getPolice_code());spUtils.put("police_name",login_user.getPolice_name());

        spUtils.put("department_id",login_user.getDepartment_id()+"");
        spUtils.put("department_name",login_user.getDepartment_name());
        spUtils.put("cusnumber",login_user.getCus_number()+"");
        spUtils.put("police_id",login_user.getPolice_id()+"");
        spUtils.put("token",login_user.getToken());
        LogUtils.e("police_code"+login_user.getPolice_code()+login_user.getPolice_name());
        MainApp.getInstance().setLoginUser(login_user);

//        getPrisonList(login_user);

        skip();

    }

    private void getPrisonList(Response_login_user user) {
        //根据民警获取罪犯列表
        Request_loadPrisonerList request_loadPrisonerList = new Request_loadPrisonerList();
        request_loadPrisonerList.setCusNumber("3223");
        request_loadPrisonerList.setDepartmentId(user.getDepartment_id()+"");
        String callroll_data = gson.toJson(request_loadPrisonerList);
//        getP().loadData(callroll_data);
    }

    public void save_data(List<Response_loadPrisonerList> persionList){

        LogUtils.e(persionList.size()+"用户");
        dBManager.deletePresion();
        if(dBManager.insertPrisonerList(persionList)){
            List<Response_loadPrisonerList> persionLists =  dBManager.queryPrisonerList();
            ToastUtils.showShort("本部门"+persionLists.size()+"名罪犯");
//            LogUtils.e(persionLists.size()+"用户");
        }else {
            LogUtils.e("没插入成功");
        }

        skip();

}

@Override
public void onWidgetClick(View view) {
        Logger.getLogger("cc");
        }

public void  skip(){
//        Intent startIntent = new Intent(LoginActivity.this, NotificationService.class);
//        startService(startIntent); // 启动服务
        //TODO 订阅消息
        MqttClientMgr.getInstance(LoginActivity.this.getApplicationContext()).subscribe("topic/" + spUtils.getString("department_id") + "/grid");
        MqttClientMgr.getInstance(LoginActivity.this.getApplicationContext()).subscribe("topic/" + spUtils.getString("department_id") + "/alarm");
        LogUtils.e("登录注册推送");
        startActivity(new Intent(LoginActivity.this, IndexActivity.class));
        finish();
        }


        }